package cn.com.web.filter;

import cn.com.domain.Customer;
import cn.com.domain.Room;
import cn.com.service.CustomerService;
import cn.com.service.RoomService;
import cn.com.service.impl.CustomerServiceImpl;
import cn.com.service.impl.RoomServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "Filter1",urlPatterns = "/*")
public class Filter1 implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //过滤器解决中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        HttpServletRequest request= (HttpServletRequest) req;
        HttpSession session = request.getSession();
        //如果customer是空就加进去
        if (session.getAttribute("customers")==null){
            CustomerService customerService=new CustomerServiceImpl();
            List<Customer> customers = customerService.findAll();
            session.setAttribute("customers",customers);
        }
        //如果rooms是空就加进去
        if (session.getAttribute("rooms")==null ){
            RoomService roomService=new RoomServiceImpl();
            List<Room> rooms = roomService.findAll();
            session.setAttribute("rooms",rooms);
        }
        //放行
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
